
from PyQt4.QtCore import Qt, SIGNAL
from PyQt4.QtGui import QTreeWidget, QTreeWidgetItem


class TreeWidget(QTreeWidget):

    def __init__(self, parent=None):
        super(TreeWidget, self).__init__(parent)

    def remove(self, item, column):
        self.removeItemWidget(item, column)

    def on_clicked(self, callback):
        self.connect(self, SIGNAL('itemClicked(QTreeWidgetItem*, int)'), callback)

    def on_double_clicked(self, callback):
        self.connect(self, SIGNAL('itemDoubleClicked(QTreeWidgetItem*, int)'), callback)

    def on_pressed(self, callback):
        self.connect(self, SIGNAL('itemPressed(QTreeWidgetItem*, int)'), callback)

    def on_collapsed(self, callback):
        self.connect(self, SIGNAL('itemCollapsed(QTreeWidgetItem*)'), callback)

    def on_expanded(self, callback):
        self.connect(self, SIGNAL('itemExpanded(QTreeWidgetItem*)'), callback)

    def on_context_menu(self, callback):
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self, SIGNAL('customContextMenuRequested(const QPoint&)'), callback)
        # self.customContextMenuRequested.connect(callback)


class TreeWidgetItem(QTreeWidgetItem):

    def __init__(self, text, parent=None):
        super(TreeWidgetItem, self).__init__(parent, [text])
        self._value = None

    def remove(self):
        parent = self.parent()
        if parent:
            parent.removeChild(self)

    def clear(self):
        count = self.childCount()
        for i in range(count - 1, -1, -1):
            item = self.child(i)
            self.removeChild(item)

    def index(self):
        parent = self.parent()
        if not parent:
            return -1
        return parent.indexOfChild(self)

    def set_text(self, text):
        index = self.index()
        if index == -1:
            return
        self.setText(index, text)

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self._value = value
